import numpy
from math import floor
import random
NONE = 0
GRID = 1
RAND = 2
JITTER = 3


def supersample(pixels, inputWidth, inputHeight, outputWidth, outputHeight, type=NONE, samples=4):
    if (type == RAND or type==JITTER):
        random.seed()
    numColours = len(pixels[0][0])
    
    pixels = numpy.reshape(pixels, (inputHeight, inputWidth, numColours))
    widthScale = inputWidth/outputWidth
    heightScale = inputHeight/outputHeight
    output = numpy.ones((outputHeight, outputWidth, numColours))
    for x in range(len(output)):
        largeX = x*widthScale
        for y in range(len(output[x])):
            largeY = y*heightScale
            for c in range(len(output[x][y])):               
                if(type == GRID):
                    values = list()
                    n = samples #n^2 is # of samples
                    for i in range(n):
                        for j in range(n):
                            xTest = floor(largeX + float(i)/float(n)*widthScale + 0.5*widthScale/float(n))
                            yTest = floor(largeY + float(j)/float(n)*heightScale + 0.5*heightScale/float(n))
                            values.append(pixels[xTest][yTest][c])
                    
                    output[x][y][c] = numpy.average(values)
                elif (type == RAND):
                    values = list()
                    n=samples*samples # num samples
                    for i in range(n):
                        xTest = floor(largeX + random.random()*widthScale)
                        yTest = floor(largeY + random.random()*heightScale)                        
                        values.append(pixels[xTest][yTest][c])
                    output[x][y][c] = numpy.average(values)
                elif (type == JITTER):
                    n = samples #n^2 is # of samples
                    for i in range(n):
                        for j in range(n):
                            xTest = floor(largeX + float(i)/float(n)*widthScale + random.random()*widthScale/float(n))
                            yTest = floor(largeY + float(j)/float(n)*heightScale + random.random()*heightScale/float(n))
                            values.append(pixels[xTest][yTest][c]) 
                    output[x][y][c] = numpy.average(values)                  
                else:    
                    output[x][y][c] = pixels[largeX][largeY][c]
        print str(float(x)/float(len(output))*100) + "% done supersampling"    
    return output
        
    
        